package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import exception.BysjException;
import util.*;
import domain.School;
import service.SchoolService;

//put,http://localhost:8080/SchoolRead.ctl
@WebServlet("/SchoolRead.ctl")
public class SchoolReadCtl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        JSONObject message_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message_jsonObj,以便往前端响应信息
        //设置响应字符编码为utf-8
        //将request body转换成JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析成JSONObject对象，可能含有分页信息
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null){
            message_jsonObj.put("message","未收到请求信息");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try{
            //读取分页信息，形成分页对象
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            //将JSON字串解析为Pagination对象
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            Collection<School> schoolList = SchoolService.getInstance().findAll(conditionList,pagination);
            message_jsonObj.put("totalNum",pagination.getTotalNum());
            message_jsonObj.put("records", schoolList);
            //分页获得所有学院
            //响应message_jsonObj到前端
            response.getWriter().println(message_jsonObj);
        }catch (BysjException e){
            message_jsonObj.put("message",e.getMessage());
            response.getWriter().println(message_jsonObj);
            e.getStackTrace();
        }catch (SQLException e){
            message_jsonObj.put("message","数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.getStackTrace();
            message_jsonObj.put("message",e.getMessage());
            response.getWriter().println(message_jsonObj);
        }catch (Exception e){
            message_jsonObj.put("message","网络异常");
            response.getWriter().println(message_jsonObj);
            e.getStackTrace();
            System.out.println(e.getMessage());
        }
    }
}
